package com.freewater.javabase.demo.network.mail;

import jakarta.activation.DataHandler;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import jakarta.mail.util.ByteArrayDataSource;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class MailSend {
    public static void main(String[] args) throws MessagingException, IOException {
        final String smtp = "smtp.126.com";
        final String username = "yujishui@126.com";
        final String password = "JMCMTITXUDZZJFUC";
        // 连接到SMTP服务器587端口:
        Properties props = new Properties();
        props.put("mail.smtp.host", smtp); // SMTP主机名
        props.put("mail.smtp.port", "25"); // 主机端口号
        props.put("mail.smtp.auth", "true"); // 是否需要用户认证
        props.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        session.setDebug(true);
        System.out.println(session);

        MimeMessage message = new MimeMessage(session);
        message.setFrom("yujishui@126.com");
        message.setSubject("测试邮件-正文携带图片", "utf-8");
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("550414715@qq.com"));
        String body = "<h1>Hello</h1><p>这是一封来自javamail的邮件</p><img src=\"cid:img01\" width=\"500\">";
        //message.setText(body, "utf-8", "html");

        Multipart multipart = new MimeMultipart();
        BodyPart textPart = new MimeBodyPart();
        textPart.setContent(body, "text/html;charset=utf-8");
        multipart.addBodyPart(textPart);

        BodyPart imagePart = new MimeBodyPart();
        imagePart.setFileName("壁纸");
        FileInputStream input = new FileInputStream(new File("/Users/freewater/壁纸/16.jpg"));
        imagePart.setDataHandler(new DataHandler(new ByteArrayDataSource(input, "image/jpeg")));
        imagePart.setHeader("Content-ID", "<img01>");
        multipart.addBodyPart(imagePart);

        message.setContent(multipart);

        Transport.send(message);
    }
}
